#include "grpc_client_pool.h"
#include <iostream>

namespace cpp_backend {
namespace framework {

GrpcClient* GrpcClientPool::get_client(const std::string& host, int port) {
    std::lock_guard<std::mutex> lock(pool_mutex_);
    
    std::string endpoint = make_endpoint(host, port);
    
    // 1. 尝试从空闲队列获取
    auto& idle_queue = idle_clients_[endpoint];
    if (!idle_queue.empty()) {
        GrpcClient* client = idle_queue.front();
        idle_queue.pop();
        return client;
    }
    
    // 2. 检查是否达到上限
    auto& client_list = clients_[endpoint];
    if (client_list.size() >= static_cast<size_t>(max_clients_per_host_)) {
        // 已达上限，等待或创建新的（简化实现：直接创建）
        std::cerr << "Warning: Exceeded max clients for " << endpoint << std::endl;
    }
    
    // 3. 创建新客户端
    auto client = std::make_unique<GrpcClient>(host, port);
    GrpcClient* client_ptr = client.get();
    client_list.push_back(std::move(client));
    
    std::cout << "Created new gRPC client for " << endpoint 
              << " (total: " << client_list.size() << ")" << std::endl;
    
    return client_ptr;
}

void GrpcClientPool::return_client(GrpcClient* client) {
    if (!client) {
        return;
    }
    
    std::lock_guard<std::mutex> lock(pool_mutex_);
    
    std::string endpoint = client->endpoint();
    
    // 归还到空闲队列
    idle_clients_[endpoint].push(client);
}

void GrpcClientPool::clear() {
    std::lock_guard<std::mutex> lock(pool_mutex_);
    
    clients_.clear();
    idle_clients_.clear();
    
    std::cout << "gRPC client pool cleared" << std::endl;
}

} // namespace framework
} // namespace cpp_backend
